package socket1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/17 15:02
 */

//Socket通信的客户端
public class ClientSocketDemo {

    public static void main(String[] args) throws IOException {


        //1.初始化Socket(ip,端口)
        Socket socket = new Socket(InetAddress.getLocalHost(),9999);
        System.out.println("客户端socket返回" + socket.getClass());

        //2.连接上服务端后，通过socket.getOutputStream()得到和socket关联的输出流对象
        OutputStream outputStream = socket.getOutputStream();

        //3.通过输出流，写入数据到数据通道
        outputStream.write("hello server".getBytes());
        //设置写入结束的标志
        socket.shutdownOutput();

        //4.通过输入流，接收服务端发过来的消息
        InputStream inputStream = socket.getInputStream();
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(buf)) != -1){
            System.out.println(new String(buf,0,readLen));
        }

        //关闭流对象和socket对象
        inputStream.close();
        outputStream.close();
        socket.close();
        System.out.println("客户端退出...");

    }
}
